package hdersr

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"repo-master/cache"
	"repo-master/melset"
	"repo-master/pkg"
	"strconv"
	"time"
)

func Dl(c *gin.Context) {
	name := c.PostForm("name")
	passes := c.PostForm("passes")

	if name == "" || passes == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_dl" + name
	json, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if json >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	var user melset.User
	err := melset.DB.Where("name=?", name).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Passes != pkg.Md5(passes) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if json == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func Add(c *gin.Context) {
	name := c.PostForm("name")
	img := c.PostForm("img")
	content := c.PostForm("content")
	time := c.PostForm("time")

	if name == "" || img == "" || content == "" || time == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := melset.Cw{
		Name:    name,
		Img:     img,
		Content: content,
		Time:    time,
	}
	err := melset.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offent := (page - 1) * size
	var count int64
	melset.DB.Model(&melset.Cw{}).Count(&count)

	var cw []melset.Cw

	redis_key := "redis_liat" + strconv.Itoa(page)
	jsonList, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if jsonList == "" {
		melset.DB.Offset(offent).Limit(size).Find(&cw)
		JsonLisr, _ := json.Marshal(cw)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonLisr, time.Hour*2)
	} else {
		json.Unmarshal([]byte(jsonList), &cw)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "常出现成功",
		"data": gin.H{
			"count": count,
			"cw":    cw,
		},
	})
	return
}
